package com.customization.api.uddi.cmd;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.api.uddi.util.XmlUtil;
import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;

import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.biz.requestFlow.SaveDetailFormDatasBiz;
import com.engine.workflow.biz.requestFlow.SaveMainFormDatasBiz;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.core.MainTableInfoEntity;
import com.engine.workflow.entity.core.RequestInfoEntity;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.util.CommonUtil;
import com.google.gson.JsonObject;
import convert.XmlTool;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.monitor.Monitor;
import weaver.workflow.monitor.MonitorDTO;
import weaver.workflow.webservices.WorkflowDetailTableInfo;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.workflow.WfFunctionManageUtil;


import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author liutaihong
 * @version 1.0.0
 * @ClassName CreateRequestCmd.java
 * @Description 创建流程
 * @createTime 2019-10-23 20:49:00
 */
public class CreateRequestCmd extends AbstractCommonCommand<Map<String,Object>> {
    private HttpServletRequest request=null;
    private HttpServletResponse response=null;
    public CreateRequestCmd(){

    }
    public  CreateRequestCmd(HttpServletRequest request, HttpServletResponse response){
        this.request=request;
        this.response=response;


        this.user= new User(1);
        this.params= ParamUtil.request2Map(request);
        Console.log("ReadDocsPictureByOrgCmd=request:"+request+";response:"+response);
        Console.log("params:"+this.params);
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> map=new HashMap<>();
        Console.log("execute");
        try {


            ServletInputStream is = request.getInputStream();
            ByteArrayOutputStream baos = null;
            baos = new ByteArrayOutputStream();
            int iLength = 1024;
            int bytesRead = 0;
            byte[] buff = new byte[iLength];
            while (true)
            {
                bytesRead = is.read(buff);
                if (bytesRead < 1)
                    break;
                baos.write(buff, 0, bytesRead);
            }
            //提交上来你的xml报文
            String impotxml= new String(baos.toByteArray(), StandardCharsets.UTF_8);
            Console.log("impotxml:"+impotxml);

            map.put("result",impotxml);



            //todo 触发流程 String requestId = requestService.createRequest(requestInfo);

            String wfid=Util.null2String(params.get("wfid"));
            Console.log("wfid:"+wfid);
            Map<String,PAResponseEntity> res=this.doCreateByXml(impotxml,wfid);
            for(Map.Entry<String, PAResponseEntity> entry : res.entrySet()){
                String mapKey = entry.getKey();
                PAResponseEntity paResponseEntity = entry.getValue();
                Map  m=new LinkedHashMap();
                m.put("code",paResponseEntity.getCode());
                m.put("errMsg",paResponseEntity.getErrMsg());
                m.put("data",paResponseEntity.getData());
                map.put("result",m);
            }






        } catch (Exception e) {
            e.printStackTrace();
            Console.log(e.toString());

        }
        return map;
    }

    public  Map<String,PAResponseEntity> doCreateByXml(String xml,String workflowId) {
        Map<String,PAResponseEntity> res =new LinkedHashMap<>();
        JSONObject reqJson= XmlUtil.documentToJSONObject(xml);
        JSONObject Envelope= reqJson.getJSONArray("Envelope").getJSONObject(0);
        JSONArray Header=Envelope.getJSONArray("Header");
        JSONArray Body=Envelope.getJSONArray("Body");

        JSONArray createReqRows=Envelope.getJSONArray("Body").getJSONObject(0).getJSONArray("createReq").getJSONObject(0).getJSONArray("row");
        for(int i =0;i<createReqRows.size(); i++){
            JSONObject row=createReqRows.getJSONObject(i);
             Console.log(row.toString());


            //封装主表数据 START
            JSONObject maindatafrom=row.getJSONArray("MAINDATA").getJSONObject(0);
            JSONArray jsonArr=new JSONArray();
            Iterator<String> it = maindatafrom.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = maindatafrom.getString(key);
                JSONObject field=new JSONObject();
                field.put("fieldName",key);
                field.put("fieldValue",value);
                jsonArr.add(field);
            }
            //封装主表数据 END


            JSONArray dtToArry=new JSONArray();
            if(row.containsKey("DETAILDATA")) {
                JSONArray detaildatafrom = row.getJSONArray("DETAILDATA");
                if(detaildatafrom!=null) {
                   Console.log("detaildatafrom:" + detaildatafrom.toString());
                    for (int j = 0; j < detaildatafrom.size(); j++) {
                        JSONObject dt = detaildatafrom.getJSONObject(j);
                        Iterator<String> it2 = dt.keySet().iterator();
                        while (it2.hasNext()) {
                            String key = it2.next();
                            JSONObject dtTo = new JSONObject();
                            Console.log("明细表名：" + key);
                            dtTo.put("tableDBName", key);

                            JSONArray dtitem = dt.getJSONArray(key).getJSONObject(0).getJSONArray("item");
                             Console.log("明细数据 dtitem:" + dtitem.toString());

                            JSONArray workflowRequestTableRecords = new JSONArray();
                            for (int k = 0; k < dtitem.size(); k++) {
                                 Console.log("----------------------------");
                                JSONObject item = dtitem.getJSONObject(k);
                                 Console.log("--------------行" + k + "-开始--------------" + item.toString());
                                Iterator<String> it3 = item.keySet().iterator();
                                JSONArray workflowRequestTableRecordsvalue = new JSONArray();
                                JSONObject workflowRequestTableRecord = new JSONObject();
                                workflowRequestTableRecord.put("recordOrder", "0");
                                JSONArray workflowRequestTableFields = new JSONArray();
                                while (it3.hasNext()) {
                                    String keys = it3.next();
                                    String value = item.getString(keys);
                                   Console.log(keys + ":" + value);
                                    JSONObject obj = new JSONObject();
                                    obj.put("fieldName", keys);
                                    obj.put("fieldValue", value);
                                    workflowRequestTableFields.add(obj);
                                }
                                 Console.log("封装之后:" + workflowRequestTableFields.toString());
                                 workflowRequestTableRecord.put("workflowRequestTableFields", workflowRequestTableFields);
                                 workflowRequestTableRecordsvalue.add(workflowRequestTableRecord);
                                 dtTo.put("workflowRequestTableRecords", workflowRequestTableRecordsvalue);
                                 Console.log("--------------行" + k + "-结束--------------" + dtTo.toString());
                            }

                            dtToArry.add(dtTo);
                        }


                    }
                }
            }else{
               Console.log("无明细节点");
            }
             Console.log("dtToArry:"+dtToArry.toString());



            //请求ID
            String requestId=""+Util.getIntValue(Util.null2String(row.get("REQUESTID")),-1);
            //流程标题
            String requestName=Util.null2String(row.get("REQUESTNAME"));
            //创建人
            int userId=Util.getIntValue(Util.null2String(row.get("CREATOR")),1);

            String forwardFlag="";
            String forwardResourceIds="";
            //主表数据
            String mainData=jsonArr.toString();

            //明细表数据
            String detailData= dtToArry.toString();
            //签字意见
            String remark=Util.null2String(row.get("REMARK"));
            //紧急程度
            String requestLevel=""+Util.getIntValue(Util.null2String(row.get("REQUESTLEVEL")),-1);
            //其他参数
            String otherParams="";


            String key =Util.null2String(row.get("KEY")).equals("") ? "DEFAULT" : Util.null2String(row.get("KEY"));


            //创建流程对象 START
            JSONObject requestinfo=new JSONObject();
            requestinfo.put("workflowId",workflowId);
            requestinfo.put("requestId",requestId);
            requestinfo.put("requestName",requestName);
            requestinfo.put("userId",userId);
            requestinfo.put("forwardFlag",forwardFlag);
            requestinfo.put("forwardResourceIds",forwardResourceIds);
            requestinfo.put("mainData",mainData);
            requestinfo.put("detailData",detailData);
            requestinfo.put("remark",remark);
            requestinfo.put("requestLevel",requestLevel);
            requestinfo.put("otherParams",otherParams);
            ReqOperateRequestEntity reqOperateRequest=request2Entity(requestinfo);


            PAResponseEntity paResponseEntity=  this.doCreateRequest(new User(userId),reqOperateRequest);
            res.put(key,paResponseEntity);

        }
        return  res;

    }




    private static ReqOperateRequestEntity request2Entity(JSONObject obj) {
        ReqOperateRequestEntity req = new ReqOperateRequestEntity();

        try {
            int workflowId = Util.getIntValue(Util.null2String(obj.get("workflowId")));
            int requestId = Util.getIntValue(Util.null2String(obj.get("requestId")));
            String requestName = Util.null2String(obj.get("requestName"));
            int userId = Util.getIntValue(Util.null2String(obj.get("userId")));
            int forwardFlag = Util.getIntValue(Util.null2String(obj.get("forwardFlag")));
            String forwardResourceIds = Util.null2String(obj.get("forwardResourceIds"));
            String mainData = Util.null2String(obj.get("mainData"));
            if (!"".equals(mainData)) {
                try {
                    List var9 = JSONObject.parseArray(mainData, WorkflowRequestTableField.class);
                    req.setMainData(var9);
                } catch (Exception e) {
                    e.printStackTrace();
                   Console.log("mainData:"+e.toString());
                }
            }

            String detailData = Util.null2String(obj.get("detailData"));
            if (!"".equals(detailData)) {
                try {
                    List var10 = JSONObject.parseArray(detailData, WorkflowDetailTableInfo.class);
                    req.setDetailData(var10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            String remark = Util.null2String(obj.get("remark"));
            String requestLevel = Util.null2String(obj.get("requestLevel"));
            String otherParams = Util.null2String(obj.get("otherParams"));
            if (!"".equals(otherParams)) {
                try {
                    Map var13 = (Map)JSONObject.parseObject(otherParams, Map.class);
                    req.setOtherParams(var13);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            req.setWorkflowId(workflowId);
            req.setRequestId(requestId);
            req.setRequestName(requestName);
            req.setUserId(userId);
            req.setRemark(remark);
            req.setRequestLevel(requestLevel);
            req.setForwardFlag(forwardFlag);
            req.setForwardResourceIds(forwardResourceIds);
            req.setClientIp(Util.null2String(obj.get("param_ip")));
            int submitNodeId = Util.getIntValue(Util.null2String(obj.get("submitNodeId")));
            if (submitNodeId > 0 || FreeNodeBiz.isFreeNode(submitNodeId)) {
                req.setSubmitNodeId(submitNodeId);
                String enableIntervenor=Util.null2String(obj.get("enableIntervenor")).equals("")?Util.null2String(obj.get("enableIntervenor")):"1";
                req.setEnableIntervenor("1".equals(enableIntervenor));
                req.setSignType(Util.getIntValue(Util.null2String(obj.get("SignType")), 0));
                req.setIntervenorid(Util.null2String(obj.get("Intervenorid")));
            }
        } catch (Exception e) {
            e.printStackTrace();

        }


        return req;
    }



    public PAResponseEntity doCreateRequest(User user, ReqOperateRequestEntity entity) {
        PAResponseEntity var3 = RequestOperateBiz.newReqVerifyParam(entity, user);
        if (var3.getCode() != null) {
            return var3;
        } else {
            entity.setRequestId(-1);
            RequestInfoEntity requestInfo = RequestOperateBiz.initRequestInfo(entity, user);
            SaveMainFormDatasBiz.initMainTableInfo(requestInfo);
            SaveDetailFormDatasBiz.initDetailTableInfo(requestInfo);
            Console.log( "RequestInfoEntity:"+requestInfo.getMainTableInfoEntity().getTableDbName());;
            //创建流程
            int requestid = RequestOperateBiz.initRequestBaseInfo(user, requestInfo, entity);

            if (requestid < 0) {
                Console.log("~~~~~创建流程失败~~~~~" + JSON.toJSONString(entity));
                var3.setCode(PAResponseCode.SYSTEM_INNER_ERROR);
                return var3;
            } else {
                HashMap var6 = new HashMap();
                var3.setData(var6);
                requestInfo.setRequestId(String.valueOf(requestid));
                var3.setCode(PAResponseCode.SUCCESS);

                Map var7;
                try {
                    if (entity.getMainData() == null || entity.getMainData().size() == 0) {
                        var3.getErrMsg().put("mainData", "新建流程主表数据不允许为空");
                        var3.setCode(PAResponseCode.PARAM_ERROR);
                        return var3;
                    }

                    var7 = new HashMap();

                   ///todo var7 = RequestOperateBiz.saveRequestInfo(requestInfo, user, entity);

                    if (var7.size() > 0) {
                        var3.setCode(PAResponseCode.PARAM_ERROR);
                        var3.setErrMsg(var7);
                        return var3;
                    }
                } catch (Exception var10) {
                    var10.printStackTrace();

                    var3.setCode(PAResponseCode.SYSTEM_INNER_ERROR);
                    var3.getErrMsg().put("saveRequestError", "流程保存失败");
                }

                var7 = entity.getOtherParams();
                boolean var8 = "1".equals(Util.null2s(Util.null2String(var7.get("isnextflow")), "1"));
                if (var8 && var3.getCode() == PAResponseCode.SUCCESS) {
                    requestInfo.setSrc("submit");
                    boolean var9 =false;//todo RequestOperateBiz.flowNextNode(requestInfo, user, entity);
                    if (!var9) {
                        var3.setCode(PAResponseCode.SYSTEM_INNER_ERROR);
                    }
                }

                if (var3.getCode() == PAResponseCode.SUCCESS) {
                    var6.put("requestid", requestid);
                } else if ("1".equals(Util.null2s(Util.null2String(var7.get("delReqFlowFaild")), "0"))) {
                    entity.setRequestId(Util.getIntValue(requestInfo.getRequestId()));
                    this.deleteRequest(user, entity);
                }

                return var3;
            }
        }
    }

    public PAResponseEntity deleteRequest(User var1, ReqOperateRequestEntity var2) {
        int var3 = var2.getRequestId();
        Map var4 = var2.getOtherParams();
        PAResponseEntity var5 = RequestOperateBiz.verifyBefore(var1, var3, var4);
        if (var5.getCode() != null) {
            return var5;
        } else {
            RequestInfoEntity var6 = RequestOperateBiz.initRequestInfo(var2, var1);

            WfFunctionManageUtil var7 = new WfFunctionManageUtil();
            boolean var8 = var7.IsShowDelButtonByReject(var3, var6.getWorkflowId());
            int var9 = var6.getIsremark();
            int var10 = var6.getTakisremark();
            boolean var11 = var8 && Util.getIntValue(var6.getCurrentNodeType()) == 0 && var9 == 0 && (var10 == 0 || var10 == -1);
            boolean var12 = "1".equals(Util.null2String(var4.get("ismonitor")));
            if (!var11 && var12) {
                MonitorDTO var13 = (new Monitor()).getMonitorInfo(String.valueOf(var1.getUID()), var6.getCreatorId(), String.valueOf(var6.getWorkflowId()));
                var11 = var13.getIsdelete();
            }

            if (var11) {
                RequestService var15 = new RequestService();
                boolean var14 = var15.deleteRequest(var3, var1.getUID());
                var5.setCode(var14 ? PAResponseCode.SUCCESS : PAResponseCode.SYSTEM_INNER_ERROR);
            } else {
                var5.setCode(PAResponseCode.NO_PERMISSION);
            }



            return var5;
        }
    }
}
